# discord bot sends memes in response to commands starting with !meme
# 
# !meme				- show random meme
# !meme category	- show meme from this category
#
import discord
from discord.ext import commands
import requests
import json
import random
import os
from sqlmodel import Field, Session, SQLModel, create_engine, select
from dotenv import load_dotenv
load_dotenv()

DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
IMG_API = os.getenv("BOT_IMG_API")

intents = discord.Intents(messages=True, guilds=True, reactions=True)
intents.message_content = True
bot = commands.Bot(command_prefix = "!", intents=intents, case_insensitive=True)


# categories and image counts stored in sqlite table
# 
#	  |  id  |   name   |  images |
#	  +------+----------+---------+
#	  |   1  |  tesla   |    19   |
#	  +------+----------+---------+
#	  |   2  |  trump   |    55   |
#	  +------+----------+---------+
#
class Cat(SQLModel, table=True):
    id: int | None = Field(default=None, primary_key=True)
    name: str
    images: int | None = None


sqlite_file_name = "memes.db"
engine = create_engine(f"sqlite:///{sqlite_file_name}", echo=False)

def select_cats() -> list:
	with Session(engine) as session:
		# SELECT * FROM `cat` WHERE `images` > 1 LIMIT 100
		statement = select(Cat).where(Cat.images > 1).limit(100)
		results = session.exec(statement)
		return results.all()

def select_cat(catname: str) -> Cat:
	with Session(engine) as session:
		statement = select(Cat).where(Cat.name == catname)
		results = session.exec(statement)
		return results.one()


# generic meme function takes optional input params to specify what type
@bot.command(aliases = ["whatever", "misc", "random"])
async def meme(context, *args):
	# if input param, use that to choose category instead of random
	if len(args) > 0:
		cat = select_cat(args[0])
	else:
		cats = select_cats()
		cat = random.choice(cats)

	imgnum = random.randint(1, cat.images)
	await context.channel.send(f'!meme _{cat.name}_ ({imgnum} of {cat.images})')
	await context.channel.send(f'{IMG_API}/{cat.name}/{imgnum}.jpg')


@meme.error
async def meme_error(context, error):
    if isinstance(error, commands.BadArgument):
        await context.channel.send('I could not find that meme...')

@bot.command()
async def about(context):
	MyEmbed = discord.Embed(title = "Bot Commands", description = "These are the commands I know:", color = discord.Colour.dark_purple())
	cats = select_cats()
	for cat in cats:
		MyEmbed.add_field(name = f"{cat.name}", value = f"this will display a random {cat.name} meme", inline = False)
	MyEmbed.set_thumbnail(url = "https://logodix.com/logo/557655.png")
	await context.send(embed = MyEmbed)

bot.run(DISCORD_TOKEN)